package com.wise.transactionsyn.sample1;

import org.springframework.transaction.support.TransactionSynchronizationAdapter;
import org.springframework.transaction.support.TransactionSynchronizationManager;

public class MyTransactionSynchronizationAdapter extends TransactionSynchronizationAdapter {
    private MySessionFactory mySessionFactory;

    public MyTransactionSynchronizationAdapter(MySessionFactory mySessionFactory) {
        this.mySessionFactory = mySessionFactory;
    }

    @Override
    public void beforeCommit(boolean readOnly) {
        //readOnly标识是否是一个只读线程
        if (!readOnly) {
            MySession mySession = (MySession) TransactionSynchronizationManager.getResource(mySessionFactory);
            mySession.beginTransaction();
        }
    }

    @Override
    public void afterCompletion(int status) {
        MySession mySession = (MySession) TransactionSynchronizationManager.getResource(mySessionFactory);
        if (STATUS_COMMITTED == status) {
            mySession.commit();
        }
    }
}
